package mall.repository;

import mall.entity.Cart;

import java.sql.ResultSet;
import java.util.List;

public class CartDao extends BaseDao<Cart> {


    @Override
    public Cart rowToObject(ResultSet rs) throws Exception {
        Cart cart = new Cart();
        cart.setId(rs.getInt("id"));
        cart.setUserId(rs.getInt("user_id"));
        cart.setProductId(rs.getInt("product_id"));
        cart.setQuantity(rs.getInt("quantity"));
        cart.setSelected(rs.getInt("selected"));
        return cart;
    }

    public int insert(Cart cart) {
        String sql = "insert into cart(user_id, product_id) values(?, ?)";
        return executeUpdate(sql, cart.getUserId(), cart.getProductId());
    }

    public List<Cart> selectListByUserId(Integer userId) {
        return executeQuery("select * from  cart where user_id = ?", userId);
    }

    public int updateQuantityById(Integer quantity, Integer id) {
        String sql = "update cart set quantity = ? where id = ?";
        return executeUpdate(sql, quantity,id);
    }

    public int deleteById(Integer cartId) {
        String sql = "delete from cart where id = ?";
        return executeUpdate(sql, cartId);
    }

    public int updateSelectedById(Integer selected, Integer cartId) {
        String sql = "update cart set selected = ? where id = ?";
        return executeUpdate(sql, selected,cartId);
    }

    public boolean getByUserIdAndProductId(Integer userId, Integer productId) {
        return !executeQuery("select * from  cart where user_id = ? and product_id = ? ", userId, productId).isEmpty();
    }
}
